package com.yld.base.dao.impl;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import com.yld.annotation.ScottTable;
import com.yld.base.dao.BaseDao;
import com.yld.user.utils.DBUtil;

public class BaseDaoImpl<T> implements BaseDao<T>{

	
	/**
	 * 泛型的具体类型
	 * @return
	 */
	public String  getType(){
		ParameterizedType type = (ParameterizedType)getClass().getGenericSuperclass();
		Type t = type.getActualTypeArguments()[0];
		System.out.println("entity="+t.getTypeName());
		
		return t.getTypeName();
	}

	@Override
	public void deleteById(Integer id) {
		
		
		//关闭的时候要遵循先进后出
		Connection connection=null;
		PreparedStatement ps = null;
		try {
			//1 连接数据库
			connection = DBUtil.getConnection();
			
			
			//表名应该是动态  注解和反射
			String teacher= getType();
			
			Class<?> clazz = Class.forName(teacher);
			
			
			ScottTable scottTable = (ScottTable)clazz.getAnnotation(ScottTable.class);
			
			String tableName=scottTable.tableName();
			
			
			//?怎么拿到T
			
			
			
			//2准备sql  我怎么知道要用哪张表删除?  用注解和反射
			String sql="DELETE FROM "+tableName+" WHERE ID=?";
			
			
			
			
			//3把字符串封装成可执行的sql命令    准备好的执行语句
			ps = connection.prepareStatement(sql);
			
			
			//4对参数给定具体的值
			
			//写死
			
			
			ps.setInt(1, id);
			
			
			
			//5执行命令
			ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			
			if(null != ps){
				try {
					ps.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if(null !=connection){
				try {
					connection.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			
		}

	}

}
